<template>
  <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules" label-width="auto"
    class="demo-ruleForm">
    <el-form-item label="账号" prop="username">
      <el-input v-model="ruleForm.username" type="username" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="ruleForm.password" type="password" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        登陆
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import router from '@/router';
import { get_lsit } from '@/api/login';
import { ElMessage } from 'element-plus'

const ruleFormRef = ref<FormInstance>()

const validatorFn = (rule: any, value: any, callback: any) => {
  const zz = /^\d{5,8}$/
  if (zz.test(value)) {
    callback()
  } else {
    callback(new Error('密码格式为5~8位'))
  }
}

const ruleForm = reactive({
  username: '',
  password: ''
})

const rules = reactive<FormRules<typeof ruleForm>>({
  username: [{ trigger: 'blur', required: true, message: '请输入账号' }],
  password: [{ trigger: 'blur', required: true, message: '请输入密码' }, {
    validator: validatorFn
  }]
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      console.log('登陆!')
      const res = await get_lsit(ruleForm)
      if (res.data.code === 200) {
        ElMessage({
          message: '登陆成功',
          type: 'success'
        })
        localStorage.setItem('token', res.data.data.token)
        router.push('/home')
      }
    } else {
      console.log('error submit!')
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
